//
//  Stackutil.m
//  V3d_Cocoa
//
//  Created by yang liang on 11-3-23.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "Stackutil.h"
#import	"Mg_image_lib.h"
#import	"Mg_utilities.h"

char * getSurfix(char *filename)
{
	if (!filename)
		return 0;
	
	V3DLONG i=0,k=-1;
	while (filename[i]!='\0')
	{
		if (filename[i]=='.')
			k=i;
		i++;
	}
	
	if (k==-1 || k==i)
		return 0;
	
	return (filename+k+1);
}

int loadTif2Stack(const char * filename, unsigned char ** img, V3DLONG **  sz, int * datatype)
{	int b_error = 0;
		
	// the following are the interface codes
	
	Stack *tmpstack = Read_Stack(filename);
	if(!tmpstack)
	{
		b_error = 1;
		return b_error;
	}
	
	if(*sz) { free(*sz); *sz = 0;}
	if(*img){ free(*img); *img = 0;}

	*sz = (V3DLONG *)Guarded_Malloc(sizeof(V3DLONG)*4,"loadTif2Stack");
	if(*sz)
	{
		(*sz)[0] = tmpstack->width;
		(*sz)[1] = tmpstack->height;
		(*sz)[2] = tmpstack->depth;
		switch(tmpstack->kind)
		{
			case GREY:
			(*sz)[3] = 1;
			*datatype = 1;
			break;
				
			case GREY16:
			(*sz)[3] = 1;
			*datatype = 2;
			break;

			case COLOR:
			(*sz)[3] = 3;
			*datatype = 1;
			break;

			default:
			printf("The type of tif file is not supported in this version.\n");
				if(*sz){ free(*sz); *sz = 0;}
				Kill_Stack(tmpstack);
				tmpstack = 0;
				return 1;
		}
	}
	else
	{
		printf("Unable to allocate memory for the size varable!Return.\n");
		if(tmpstack)
		{
			Kill_Stack(tmpstack);
			tmpstack = 0;
		}
		b_error = 1;
		return b_error;
	}

	*img = (unsigned char *) Guarded_Malloc((*sz)[0]*(*sz)[1]*(*sz)[2]*(*sz)[3]*(*datatype),"loadTif2Stack");
	if(!(*img))
	{
		printf("Unable to allocate memory for the image varable!Return.\n");
		if(tmpstack){Kill_Stack(tmpstack); tmpstack = 0;}
		if(*sz){free(*sz); *sz = 0;}
		b_error = 1;
		return b_error;
	}
	else
	{
		V3DLONG i,j,k,c;
		V3DLONG pgsz1 = (*sz)[2]*(*sz)[1]*(*sz)[0],pgsz2 = (*sz)[1]*(*sz)[0],pgsz3 = (*sz)[0];

		switch(tmpstack->kind)
		{
			case GREY:
			case COLOR:
				for (c=0;c<(*sz)[3];c++)
					for (k=0;k<(*sz)[2]; k++)
						for (j=0;j<(*sz)[1]; j++)
							for (i=0;i<(*sz)[0]; i++)
								(*img)[c*pgsz1 + k*pgsz2 + j*pgsz3 + i] = Get_Stack_Pixel(tmpstack,i,j,k,c);
				
				break;
				
			case GREY16:
				{
					unsigned short int *img16 = (unsigned short int *)(*img);
					for (c=0;c<(*sz)[3];c++)
						for (k=0;k<(*sz)[2]; k++)
							for (j=0;j<(*sz)[1]; j++)
								for (i=0;i<(*sz)[0]; i++)
									img16[c*pgsz1 + k*pgsz2 + j*pgsz3 + i] = Get_Stack_Pixel(tmpstack,i,j,k,c); 
				}
				
				break;
		
			default:
			printf("The type of the tile file is not supported in this version.\n");
			if(*sz){free(*sz); *sz = 0;}
				if(*img){free(*img); *img = 0;}
				Kill_Stack(tmpstack);tmpstack = 0;
			b_error = 1;
			return b_error;
			break;
		}
	}
	
	if(tmpstack)
	{
		Kill_Stack(tmpstack);
		tmpstack = 0;
	}
	return b_error;
}